<template>
  <div id="app" class="store-out-single">
    <!-- 头部导航 -->
    <van-nav-bar ref="header" title="坯布出库" left-arrow @click-left="comeBack" left-text="返回" >
      <template #right>
        <span @click="openToScanFn"><van-icon name="scan" size="20" /></span>
      </template>
    </van-nav-bar>
    <!-- 当前扫码总数 -->
    <van-cell class="store-out__cell" v-show="clothData.length !== 0" :title="'总计匹数'" :value="clothData.length"></van-cell>

    <!-- 滚动 -->
    <better-scroll ref="bodyListRef" class="public-scroll" :data="clothData" :totalPage="clothTotalPage">
      <van-cell-group v-show="clothData.length !== 0">
        <van-swipe-cell v-for="(data, index) in clothData" :key="index">
          <van-cell :title="'品号: ' + data.embroideryNo">
            <template slot="label">
              <div class="store-in-cell">
                <span>
                  <span>色号: </span>
                  <van-field readonly :value="data.colorNo"/>
                </span>
                <span>
                  <span>匹号: </span>
                  <van-field readonly :value="data.designSeqNo"/>
                </span>
                <span>
                  <span>区域: </span>
                  <van-field readonly :value="data.area"/>
                </span>
                <span>
                  <span>重量: </span>
                  <van-field readonly :value="data.weight"/>
                </span>
                <span>
                  <span>长度: </span>
                  <van-field readonly :value="data.length"/>
                </span>
                <span>
                  <span>织机号: </span>
                  <van-field readonly :value="data.loomNo"/>
                </span>
              </div>
            </template>
          </van-cell>
          <template #right>
            <van-button
                square
                type="danger"
                text="删除"
                @click="deleteClothFn(index)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>
      <van-empty
          class="custom-image"
          image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
          v-show="clothData.length === 0"
          description="暂无数据"
      />
    </better-scroll>

    <!-- 底部按钮 -->
    <div ref="footer" class="store-out-btn">
      <van-button block type="info" class="bgColor" @click="confirmToOutFn">确认出库</van-button>
    </div>
  </div>
</template>

<script>
import { greyClothAreaNums, getGreyClothGet, greyClothStoreOutConfirm} from "@/api/cloth";
import {comeBack, openWin} from "@/utils";
import {getMacAddress} from "@/utils/auth";
import dayjs from "dayjs";

export default {
  name: "storeOutSingle",
  data() {
    return {
      clothData: [],
      clothTotalPage: 0,
      listHeight: 600,

      /* 确认出库相关 */
      storeGroup: null,   //扫码后的坯布分组,每次确认都新生成咯对象,免得复杂
      printedStoreId: 0,

      /* 打印相关 */
      connectionStatus: false,    //打印机状态
      printStatus: true,
      printRow: {},
      designNo: "",
      color: "",
      num: "",

    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      }
    }
  },
  methods: {
    comeBack,

    //初始化
    initFn(that) {

    },

    //打开扫码窗口
    openToScanFn() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          if(!Number.isInteger(parseInt(ret.result))) {
            that.$toast.fail("请扫坯布二维码");
            return false;
          }
          getGreyClothGet(ret.result, greyCloth => {
            let loadingMsg = "请继续下一个";
            that.clothData.forEach((item) => {
              if (item.id == ret.result) {
                loadingMsg = "当前扫描的已存在,将继续下一个";
              }
            });
            if(greyCloth.status != 2) {
              loadingMsg = "当前扫描的不是入库状态,将继续下一个";
            }
            if(greyCloth.storeId == 0) {
              that.$toast.fail("该匹布没有对应的仓库信息,需要单独处理");
              return;
            }
            if("请继续下一个" == loadingMsg) {
              that.clothData.push(greyCloth);
            }

            that.$toast({
              type: "loading",
              message: loadingMsg,
              duration: 1000,
              onClose: () => {
                that.openToScanFn();
              },
            });
          });
        }
      });
    },

    //删除选中行
    deleteClothFn(index) {
      let that = this;
      that.clothData.splice(index, 1);
    },

    //确认出库
    confirmToOutFn() {
      let that = this;

      //按storeId分组
      that.storeGroup = {};
      that.clothData.forEach(greyCloth => {
        let storeId = greyCloth.storeId;
        let group = (that.storeGroup[storeId] = that.storeGroup[storeId] ? that.storeGroup[storeId] : []);   //每次新声明个数组,免得复杂化
        group.push(greyCloth);
      });

      //逐组处理 打印完一组再打印下一组
      let firstKey = Object.keys(that.storeGroup)[0];
      that.confirmToOutSingleFn(that, firstKey, that.storeGroup[firstKey]);
    },
    //出库回调
    confirmToOutSingleFn(that, storeId, greyCloths) {
      greyClothAreaNums({ storeId: storeId }, areaNumInfo => {
        let areaNums = areaNumInfo.areaNums;
        if (areaNums.totalNum == 0) {
          that.$toast.fail('当前坯布库存为0:' + greyCloths[0].designNo);
          return false
        }

        //按区域分组
        let areaGroup = {};
        greyCloths.forEach(greyCloth => {
          let area = greyCloth.area;
          let group = (areaGroup[area] = areaGroup[area] ? areaGroup[area] : []);
          group.push(greyCloth);
        });
        let msg = "";   //错误信息
        areaNums.forEach(areaNum => {
          if(msg != "") {
            that.$toast.fail(msg);
            return;
          }
          let areas = areaNum.split("_");
          if(areaGroup[areas[0]]) {
            if(areaGroup[areas[0]].length > parseInt(areas[1])) {   //实际库存不足
              msg = ("区域库存不足:" + greyCloths[0].designNo + " 区域:" + areas[0] + " 实际库存:" + areas[1] + " 需要:" + areaGroup[areas[0]].length);
              return;
            } else {
              //加出库单
              greyClothStoreOutConfirm({
                storeId: storeId,
                area: areas[0],
                greyClothId: greyCloths[0].id,
                num: greyCloths.length
              }, (res) => {
                if (!getMacAddress()) {
                  that.$toast.fail("出库成功，如需打印，请退出登录选择打印机");
                  return false;
                }
                that.$toast({
                  type: "success",
                  message: "出库成功，打印中",
                  duration: 1000,
                  onClose: () => {
                    that.printRow = res;
                    that.printedStoreId = storeId;    //当前处理的
                    that.printRow.designNo = greyCloths[0].designNo;
                    that.printRow.color = greyCloths[0].colorNo;
                    that.getConnectState();
                  },
                });
              });
            }
          }
        });
      });
    },

    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      let obj = window.api.require("xGprinterPlus");
      let ret = obj.getConnectState();
      if (ret.status) {   //已连接
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddressFn();
            },
          });
        }
      } else {    // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddressFn();
          },
        });
      }
    },
    // 连接蓝牙
    connectBleByMacAddressFn() {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      let demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress({
        macAddress: getMacAddress() ? getMacAddress().address : "",
      }, (ret, err) => {
        if (ret.status) {
          if (ret.message === "已连接") {
            that.connectionStatus = true;
            if (that.printStatus) {
              that.$toast({
                type: "success",
                message: "连接成功",
                duration: 1500,
                onClose: () => {
                  that.printLabel();
                },
              });
            }
          } else if (ret.message === "连接失败") {
            that.connectionStatus = false;
            that.$toast({
              type: "fail",
              message: "初始化失败",
              duration: 1500,
            });
          } else {
            that.connectionStatus = false;
          }
        } else {
          that.$toast({
            type: "fail",
            message: err.msg,
            duration: 1500,
          });
        }
      });
    },
    // 打印数据
    printLabel() {
      const that = this;
      let obj = window.api.require("xGprinterPlus");
      obj.printLabel({
        rows: [{
          lineType: "size",
          width: 50,
          height: 70,
        }, {
          lineType: "gap",
          data: 3,
        }, {
            lineType: "cls",
        }, {
          // 图片单元格竖线
          lineType: "bar",
          x: 25 + 130,
          y: 0,
          width: 2,
          height: 136,
        }, {
          //绘制图片
          lineType: "image",
          x: 25 + 8,
          y: 8,
          data: "widget://image/huibo_logo.png",
        }, {
          //绘制文本
          lineType: "text",
          x: 25 + 8,
          y: 10,
          rotation: 0,
          xscal: 1,
          yscal: 1,
          data: "艺多染整",
        }, {
          // 横线
          lineType: "bar",
          x: 25 + 4,
          y: 186,
          width: 130,
          height: 2,
        }, {
          //绘制文本
          lineType: "text",
          x: 25 + 4,
          y: 136 + 2,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: dayjs().format("YYYY-MM-DD"),
        }, {
          // 横线
          lineType: "bar",
          x: 25,
          y: 236,
          width: 608,
          height: 2,
        }, {
          //绘制文本
          lineType: "text",
          x: 25 + 8,
          y: 236,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "坯布出库码（" + that.printRow.id.toString() + "）",
        }, {
          lineType: "qrcode", // 绘制qrcode
          x: 25 + 150 + 2,
          y: 10,
          level: "L", //L|M|H|Q
          cellwith: 9,
          rotation: 0, // 0|90|180|270
          data: "13," + that.printRow.id.toString(),
        }, {
          //绘制文本
          lineType: "text",
          x: 25 + 4,
          y: 286 + 2,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "品名: " + that.printRow.designNo,
        }, {
          // 横线
          lineType: "bar",
          x: 25,
          y: 286,
          width: 608,
          height: 2,
        }, {
          //绘制文本
          lineType: "text",
          x: 25 + 4,
          y: 336 + 2,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "色号: " + that.printRow.color,
        }, {
          // 横线
          lineType: "bar",
          x: 25,
          y: 336,
          width: 608,
          height: 2,
        }, {
          //绘制文本
          lineType: "text",
          x: 25 + 4,
          y: 386 + 2,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "出库数量: " + that.printRow.num,
        }, {
          //绘制文本
          lineType: "text",
          x: 25 + 4,
          y: 436 + 2,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "操作人: " + that.printRow.optName,
        }, {
          // 横线
          lineType: "bar",
          x: 25,
          y: 436,
          width: 608,
          height: 2,
        }, {
          // 横线
          lineType: "bar",
          x: 25,
          y: 486,
          width: 608,
          height: 2,
        }]
      }, (ret, err) => {
        if (ret.status) {
          that.$toast({
            type: "success",
            message: "打印成功",
            onClose: () => {
              //移除已打印的
              if(that.storeGroup && that.storeGroup[that.printedStoreId]) {
                let printedGreyCloth = that.storeGroup[that.printedStoreId];
                printedGreyCloth.forEach(greyCloth => {
                  that.clothData.splice(that.clothData.findIndex(old => old.id == greyCloth.id), 1);
                });

                //删除那个属性
                delete that.storeGroup[that.printedStoreId];

                //继续下一次
                let firstKey = Object.keys(that.storeGroup)[0];
                if(firstKey) {
                  that.confirmToOutSingleFn(that, firstKey, that.storeGroup[firstKey]);
                } else {
                  // comeBack();
                }
              } else {
                // comeBack();
              }
            },
          });
        } else {
          that.$toast({
            type: "fail",
            message: err.code + err.msg,
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddressFn();
            },
          });
        }
      });
    }

  }
}
</script>

<style lang="scss">
.store-out-single {

  //总计匹数
  .store-out__cell {
    .van-cell__title {
      flex: 0 0 67%;
      display: flex;
      justify-content: space-between;
      span,
      .van-cell__label {
        display: flex;
        flex: 1;
      }
      .van-cell__label {
        justify-content: center;
      }
    }
    .van-cell__value {
      flex: 0 0 33%;
    }
    span,
    .van-cell__label {
      font-weight: 900;
      color: #96b327;
      font-size: 14px;
    }
  }

  //列表内容
  .public-scroll {
    height: 80vh;
    overflow: hidden;
    .store-in-cell {
      display: flex;
      flex-wrap: wrap;
      padding-top: 0;
      & > span {
        display: flex;
        width: 50%;
        height: 30px;
        align-items: center;
        & > span {
          width: 100px;
        }
        .van-cell.van-field {
          padding-left: 0;
        }
      }
    }
  }

  //底部按钮
  .store-out-btn {
    padding: 16px;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
}
</style>